"use strict";
const common_vendor = require("../../common/vendor.js");
const utils_api = require("../../utils/api.js");
const _sfc_main = {
  __name: "chapter",
  setup(__props) {
    const chapterInfo = common_vendor.ref({});
    const totalChapters = common_vendor.ref(0);
    const courseId = common_vendor.ref(null);
    const showModal = common_vendor.ref(false);
    const loading = common_vendor.ref(false);
    const chatList = common_vendor.ref([]);
    const scrollTop = common_vendor.ref(0);
    const inputMessage = common_vendor.ref("");
    const startTime = common_vendor.ref(0);
    const watchDuration = common_vendor.ref(0);
    const timer = common_vendor.ref(null);
    common_vendor.onMounted(() => {
      try {
        const pages = getCurrentPages();
        if (!pages || pages.length === 0) {
          throw new Error('无法获取页面栈信息');
        }

        const currentPage = pages[pages.length - 1];
        
        // 尝试多种方式获取页面参数
        let options = null;
        
        // 方式1: 直接从options获取
        if (currentPage && currentPage.options) {
          options = currentPage.options;
        } 
        // 方式2: 从$page.options获取
        else if (currentPage && currentPage.$page && currentPage.$page.options) {
          options = currentPage.$page.options;
        }
        // 方式3: 从route和query获取
        else if (currentPage && currentPage.$page && currentPage.$page.query) {
          options = currentPage.$page.query;
        }

        if (!options || !options.id) {
          // 尝试从storage中获取courseId
          const storedChapter = common_vendor.index.getStorageSync("currentChapter");
          if (storedChapter && storedChapter.courseId) {
            courseId.value = storedChapter.courseId;
          } else {
            throw new Error('课程ID不存在');
          }
        } else {
          courseId.value = options.id;
        }

        // 获取章节信息
        const info = common_vendor.index.getStorageSync("currentChapter");
        if (!info) {
          common_vendor.index.showToast({
            title: "章节信息不存在",
            icon: "none",
            duration: 2000
          });
          setTimeout(() => {
            common_vendor.index.navigateBack();
          }, 1500);
          return;
        }

        // 设置章节信息
        chapterInfo.value = info;

        // 获取课程详情
        const courseDetail = common_vendor.index.getStorageSync("currentCourse");
        if (courseDetail && courseDetail.chapters) {
          totalChapters.value = courseDetail.chapters.length;
        } else {
          totalChapters.value = 3;
        }

        // 开始计时
        startTime.value = Date.now();
        timer.value = setInterval(() => {
          watchDuration.value = Math.floor((Date.now() - startTime.value) / 1e3);
        }, 1e3);

      } catch (error) {
        console.error('页面初始化失败:', error);
        // 添加更多调试信息
        console.log('当前页面信息:', {
          pages: getCurrentPages(),
          currentPage: getCurrentPages()[getCurrentPages().length - 1],
          storage: {
            chapter: common_vendor.index.getStorageSync("currentChapter"),
            course: common_vendor.index.getStorageSync("currentCourse")
          }
        });
        
        common_vendor.index.showToast({
          title: error.message || '页面加载失败',
          icon: 'none',
          duration: 2000
        });
        setTimeout(() => {
          common_vendor.index.navigateBack();
        }, 1500);
      }
    });
    common_vendor.onBeforeUnmount(() => {
      if (timer.value) {
        clearInterval(timer.value);
        saveWatchRecord();
      }
    });
    const saveWatchRecord = async () => {
      var _a;
      try {
        // 添加参数验证
        if (!courseId.value || !chapterInfo.value?.id || !watchDuration.value) {
          console.warn('保存观看记录参数不完整，跳过保存');
          return;
        }

        const res = await utils_api.courseApi.saveWatchRecord(
          courseId.value, 
          chapterInfo.value.id, 
          watchDuration.value
        );

        if (res.statusCode === 200 && res.data.code === 0) {
          console.log("观看记录保存成功", {
            courseId: courseId.value,
            chapterId: chapterInfo.value.id,
            duration: watchDuration.value
          });
          // 可以选择是否显示成功提示
          // common_vendor.index.showToast({
          //   title: '观看记录已保存',
          //   icon: 'success',
          //   duration: 1500
          // });
        } else {
          throw new Error(((_a = res.data) == null ? void 0 : _a.message) || "保存观看记录失败");
        }
      } catch (error) {
        console.error("保存观看记录失败:", error, {
          courseId: courseId.value,
          chapterId: chapterInfo.value?.id,
          duration: watchDuration.value
        });
        
        // 只在开发环境显示错误提示
        if (process.env.NODE_ENV === 'development') {
          common_vendor.index.showToast({
            title: '观看记录保存失败',
            icon: 'none',
            duration: 2000
          });
        }
      }
    };
    const showAIModal = () => {
      showModal.value = true;
    };
    const closeAIModal = () => {
      showModal.value = false;
    };
    const handleSend = async () => {
      const message = inputMessage.value.trim();
      if (!message || loading.value)
        return;
      loading.value = true;
      try {
        chatList.value.push({
          type: "user",
          content: message
        });
        chatList.value.push({
          type: "loading"
        });
        inputMessage.value = "";
        scrollToBottom();

        // 使用 Promise 包装请求
        const response = await new Promise((resolve, reject) => {
          common_vendor.index.request({
            url: "http://localhost:8080/api/AI",  // 添加完整的基础URL
            method: "POST",
            data: {
              message,
              chapterId: chapterInfo.value.id
            },
            header: {
              'content-type': 'application/json'
            },
            success: (res) => {
              resolve(res);
            },
            fail: (err) => {
              console.error('请求失败详情:', err);
              reject(new Error(err.errMsg || '网络请求失败'));
            }
          });
        });

        // 处理响应
        if (response.statusCode === 200) {
          if (response.data.code === 0) {
            chatList.value.pop();
            chatList.value.push({
              type: "ai",
              content: response.data.data.aimessage
            });
            scrollToBottom();
          } else {
            throw new Error(response.data.message || "请求失败");
          }
        } else {
          throw new Error(`请求失败，状态码：${response.statusCode}`);
        }

      } catch (error) {
        chatList.value.pop();
        console.error("发送消息失败:", error);
        
        // 更友好的错误提示
        let errorMessage = "发送失败";
        if (error.message.includes('fail')) {
          errorMessage = "网络连接失败，请检查网络设置";
        } else if (error.message.includes('timeout')) {
          errorMessage = "请求超时，请稍后重试";
        }
        
        common_vendor.index.showToast({
          title: errorMessage,
          icon: "none",
          duration: 2000
        });
      } finally {
        loading.value = false;
      }
    };
    const scrollToBottom = () => {
      setTimeout(() => {
        scrollTop.value = 9999;
      }, 100);
    };
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: common_vendor.t(chapterInfo.value.courseTitle),
        b: common_vendor.t(chapterInfo.value.index),
        c: common_vendor.t(chapterInfo.value.title),
        d: common_vendor.t(Math.floor(watchDuration.value / 60)),
        e: common_vendor.t(watchDuration.value % 60),
        f: chapterInfo.value.content,
        g: common_vendor.o(showAIModal),
        h: showModal.value
      }, showModal.value ? {
        i: common_vendor.o(closeAIModal),
        j: common_vendor.o(closeAIModal),
        k: common_vendor.f(chatList.value, (item, index, i0) => {
          return common_vendor.e({
            a: item.type === "loading"
          }, item.type === "loading" ? {} : {
            b: common_vendor.t(item.content)
          }, {
            c: common_vendor.n(item.type),
            d: index
          });
        }),
        l: scrollTop.value,
        m: loading.value,
        n: common_vendor.o(handleSend),
        o: inputMessage.value,
        p: common_vendor.o(($event) => inputMessage.value = $event.detail.value),
        q: common_vendor.t(loading.value ? "思考中..." : "发送"),
        r: common_vendor.o(handleSend),
        s: !inputMessage.value.trim() || loading.value
      } : {});
    };
  }
};
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-47fae316"]]);
wx.createPage(MiniProgramPage);
